<template>
	<view id="posts">
		<view class="comm">
			<classify @Child="selestClassifyIndex" :childIndex="Number(childIndex)" :postsAllTitle="title"
				:iconFlag="true" :list="postsAllText">
			</classify>
		</view>
		<view class="textarea">
			<view class="posts_title title1">
				<view class=" custom-icon custom-icon-biaotiqian"></view>
				<view class="title">输入标题</view>
			</view>
			<u--input placeholder="请输入标题" v-model="titleInput" border="surround" clearable></u--input>
		</view>
		<view class="textarea">
			<view class="posts_title title1">
				<view class=" custom-icon custom-icon-biaotiqian"></view>
				<view class="title">输入内容</view>
			</view>
			<u--textarea v-model="contentText" :placeholderStyle="`font-size: 24rpx;`" placeholder="再次编辑,发表你的看法"
				:maxlength="200" count></u--textarea>
		</view>
		<view class="ImageUpload">
			<view class="posts_title">
				<view class=" custom-icon custom-icon-biaotiqian"></view>
				<view class="title">上传图片/视频音频</view>
			</view>
		</view>
		<view class="info-box">
			<block>
				<view class="image-list">
					<view class="item" v-for="(item, index) in imgArr" :key="index">
						<image class="image" :src="item" mode="aspectFill"></image>
						<image class="icon" src="/static/PlayWith/close2.png" mode="widthFix"
							@click="deleteImage(index)"></image>
					</view>
				</view>
			</block>
			<!-- v-if="type == 'video'" -->
			<block v-if="type == 'video'">
				<view class="video">
					<video id="myVideo" v-if="videoPath" :src="videoPath" :controls="false" :show-fullscreen-btn="true"
						:enable-progress-gesture="false">
						<cover-image class="icon" src="/static/PlayWith/close2.png" @click="deleteSound('videoPath')">
						</cover-image>
					</video>

				</view>
			</block>
			<!-- v-if="type == 'sound'" -->
			<block v-if="type == 'sound'">
				<view class="sound">
					<image class="sound-bg" src="/static/logo.png" mode="aspectFill"></image>
					<image v-if="soundType" @click="soundPlay(1)" class="play" src="/static/PlayWith/soundSuspend.png"
						mode=""></image>
					<image v-else @click="soundPlay(2)" class="play" src="/static/PlayWith/soundPlay.png" mode="">
					</image>
					<image class="icon" src="/static/PlayWith/close2.png" mode="widthFix"
						@click="deleteSound('soundPath')">
					</image>
				</view>
			</block>
		</view>
		<view class="icon-box">
			<image src="/static/PlayWith/pic.png" mode="widthFix" @click="upload('image')"></image>
			<image src="/static/PlayWith/video.png" mode="widthFix" @click="upload('video')"></image>
			<image src="/static/PlayWith/sound.png" mode="widthFix" @click="uploadSound('sound')"></image>
			<!-- <image src="../../static/icon/turnText.png" mode="widthFix" @click="turnText"></image> -->
		</view>

		<view class="vote">
			<u-collapse @change="changeVote"  @close="close" @open="open" :border="false">
				<u-collapse-item title="选择方案">
					<view class="a" v-for="(item, index) in schemeList" :key="item.id" @click="selectScheme(item.id)"
						:class="{ selected: schemeIndex === item.id }">
						<view>
							{{ item.name }}
						</view>
					</view>
				</u-collapse-item>
				<!-- 图标，更改了插件源代码，源代码被注释， -->
				<u-collapse-item title="加入作品集">

					<view class="opusList" v-for="(opusItem,opusIndex) in opusMapList" @click="selectIndex(opusItem)"
						:key="opusIndex" :class="{'active': OpusIndex === opusItem.id}">
						<view>{{opusItem.title}}</view>
					</view>
				</u-collapse-item>
				<u-collapse-item title="权限设置">
					<view class="Permissions_type">
						<u-radio-group v-model="radiovalue1" placement="column" @change="groupChange">
							<u-radio :customStyle="{marginBottom: '8px'}" v-for="(item, index) in radiolist1"
								:key="index" :label="item.name" :name="item.name" @change="radioChange">
							</u-radio>
							<view class="PermissionsInput">
								金额：<u--input class="custom-placeholder" placeholder="0.00" border="bottom"
									clearable></u--input>

							</view>
						</u-radio-group>
					</view>
				</u-collapse-item>
			</u-collapse>


		</view>
		<view class="posts-button">
			<view class="sunbmit">
				<button @click="sunbmit(1)">发布动态</button>
				<view class="custom-icon custom-icon-dingshifabu"></view>
			</view>
			<view class="Save" @click="sunbmit(2)">
				<button>保存草稿</button>
			</view>
		</view>
		<view style="height: 100rpx;" />
	</view>
</template>

<script>
	import {
		watch
	} from "vue";
	import {
		uploadFile,
		uploadMp3File,
		uploadImgVideo,
		checkPermission
	} from '@/store/upload.js';
	const innerAudioContext = uni.createInnerAudioContext();
	innerAudioContext.autoplay = true;
	export default {
		data() {
			return {
				updAndDelId: '', //修改或删除才用
				childIndex: '', //修改或删除才用

				defaultDate: '',

				activeIndex: 1, // 当前激活的标签索引(选择模式)
				classifyIndex: '', //发布分区索引
				contentText: '',
				titleInput: '', //标题
				images: "", //上传后的图片地址
				video: "", //视频
				voice: "", //音频
				schemeIndex: '', //选择方案的索引
				OpusIndex: '', //作品集

				radiovalue1: '',
				radiolist1: [{
					name: '单帖解锁',
					disabled: false
				}, {
					name: '月度解锁',
					disabled: false
				}, {
					name: '季度解锁',
					disabled: false
				}], //权限设置的数据

				fields: {
					activeIndex: this.activeIndex,
					classifyIndex: this.classifyIndex,
					contentText: this.contentText,
					images: this.images,
					schemeIndex: this.schemeIndex,
					OpusIndex: this.OpusIndex,
				},

				// 作品集list
				opusMapList: [],
				opusMapTile: '作品集',
				title: '发布分区',
				question: '', //投票问题1
				answer: '', //投票问题2
				range: '',
				accept: 'video', //上传类型
				fileList1: [], //上传图片/视频

				maxlength: 110,

				tagTextList: ['图片', '视频', '音频'],
				schemeList: [],
				postsAllTItle: '发布分区',
				postsAllText: [],
				postsActiveIndex: null, // 用于存储当前点击的索引
				imgs: [],
				//
				type: '', //image  video  sound
				maxImage: 15,
				imgArr: [],
				videoPath: '',
				soundPath: '',
				soundType: true, // 声音播放状态

				intervalTime: 0,
				timer: null,
				isRecord: false, // 记录状态,录音中或者是未开始
				voicePath: '', // 语音路径
				soundTextShow: false, // 录音转文字
				soundTextTitle: '语音转文字',
				soundText: '按住说话',
			}
		},
		watch: {

			activeIndex(newValue, oldValue) {


				console.log("this.activeIndex,", this.activeIndex);
			}
		},

		onLoad() {
			// 监听事件
			innerAudioContext.onEnded(() => {
				this.soundType = true
			})
			uni.$on('successPath', (res) => {
				uni.showLoading({
					title: '上传中'
				})
				uploadFile([res]).then(res2 => {
					this.soundPath = res2[0]
					this.type = 'sound'
					uni.hideLoading()
				})
			})
		},
		onShow() {
			uni.getStorage({
				key: 'updAndDelId',
				success: (res) => {
					this.updAndDelId = res.data;
					console.log("修改，", this.updAndDelId); // 这里是传递过来的参数
				},
			});
			console.log("!this.updAndDelId", this.updAndDelId)
			if (this.updAndDelId) {
				this.getDynamicDetail();
			}
			uni.removeStorage({
				key: 'updAndDelId'
			});
		},
		mounted() {


			// 获取动态分类列表
			this.$api.getCateList().then(res => {
				this.postsAllText = res.data;
			});
			// 选择方案分类
			this.$api.getProgrammeList().then(res => {
				this.schemeList = res.data;
				console.log("this.schemeList", this.schemeList);
			})
			// 作品集
			this.$api.getList().then(res => {
				this.opusMapList = res.data;
				console.log("this.opusMapList", this.opusMapList);
			})
		},
		methods: {
			// 单选框的方法
			radioChange(value) {
				console.log("单选框值改变:", value);
				// 处理逻辑
			},
			groupChange(value) {
				console.log("组单选框值改变:", value);
				// 处理逻辑
			},
			getDynamicDetail() {
				// dynamicDetail
				this.$api.getDynamicDetail({
					id: this.updAndDelId
				}).then(res => {
					console.log("res=>", res.data)
					const updAndDel = res.data;
					this.childIndex = parseFloat(updAndDel.dynamic_cate_id); //发布分区索引
					this.contentText = updAndDel.content;
					this.titleInput = updAndDel.title; //标题
					this.imgArr = updAndDel.slider; //上传后的图片地址
					this.videoPath = updAndDel.video; //视频
					this.soundPath = updAndDel.voice; //音频
					this.schemeIndex = updAndDel.programme_id.id; //选择方案的索引
					this.OpusIndex = parseFloat(updAndDel.portfolio_ids);; //作品集
					console.log(this.childIndex, "+", this.OpusIndex)
				})
			},
			// 作品集选择
			selectIndex(item) {
				this.OpusIndex = item.id;
			},
			selestClassifyIndex(data) {
				this.classifyIndex = data
				console.log("父", data)
			},
			sunbmit(index) {
				const allFilled = Object.values(this.fields).every(value => value);
				if (!this.updAndDelId) {
					if (!allFilled) {
						this.$api.getReleased({
							dynamic_cate_id: this.classifyIndex, //发布分区索引
							title: this.titleInput,
							content: this.contentText,
							slider: this.images, //上传后的图片地址
							video: this.videoPath,
							voice: '',
							programme_id: this.schemeIndex, //选择方案的索引
							portfolio_ids: this.OpusIndex, //作品集
							vote_id: 1,
							types: index
						}).then(res => {
							if (res.code == 1) {
								uni.showModal({
									content: "发布成功",
									success: function(res) {
										if (res.confirm) {
											uni.reLaunch({
												url: "/pages/posts/posts"
											})
											uni.switchTab({
												url: '/pages/tabBarHome/home' // 替换为目标页面的路径
											});
										} else if (res.cancel) {
											uni.reLaunch({
												url: "/pages/posts/posts"
											})
										}
									}
								})
							}
						})

					} else {
						console.log(this.classifyIndex)
						console.log(this.contentText)
						console.log(this.images)
						console.log(this.schemeIndex)
						console.log(this.OpusIndex)
						uni.showModal({
							content: "您有未填写的选项"
						});
					}
				} else {
					console.log("修改")
					this.$api.getDynamicEdit({
						id: this.updAndDelId,
						title: this.titleInput,
						content: this.contentText,
						slider: this.images, //上传后的图片地址
						video: this.videoPath,
						voice: '',
						programme_id: this.schemeIndex, //选择方案的索引
						portfolio_ids: this.OpusIndex, //作品集
						vote_id: 1,
						types: index
					}).then(res => {
						console.log("res=>", res)
					})
				}




			},
			open(e) {
				console.log('open', e)
			},
			changeVote(e) {
				console.log('change', e)
			},
			close(e) {
				// console.log('close', e)
			},
			// 选择方案
			selectScheme(index) {
				this.schemeIndex = index;
				console.log(index)
			},
			// 加入作品集
			selectOpus(index) {
				console.log(index)
			},
			// 选择模式，上传文件类型
			/* handleTagClick(index) {
				uni.showModal({
					content: "更换后,填写的内容将失效",
					success: (res) => { // 新增：成功回调
						if (res.confirm) {
							this.activeIndex = index
							if (this.activeIndex === 0) {
								this.accept = 'image'; // 选择图片
							} else if (index === 1) {
								this.accept = 'video'; // 选择视频
							} else if (index === 2) {
								this.accept = 'audio'; // 选择音频
							}
							this.classifyIndex = ''
							this.contentText = ''
							this.images = ""
							this.schemeIndex = ''
							this.OpusIndex = ''
							this.fileList1 = []
						}
					}
				})

			}, */
			setActive(index) {
				this.postsActiveIndex = index; // 更新当前激活的索引
			},

			// 删除图片
			deletePic(event) {
				this[`fileList${event.name}`].splice(event.index, 1)
			},
			// 新增图片
			async afterRead(event) {
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this[`fileList${event.name}`].length
				console.log("fileListLen", fileListLen)
				console.log("event", event)
				console.log("lists", lists)
				lists.map((item) => {
					this[`fileList${event.name}`].push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {

					const image = await uploadFile([event.file[i].url]);
					this.imgs.push(image)
					console.log("数组", this.imgs[i][0])
					const result = await this.uploadFilePromise(this.imgs[i][0])
					console.log("result", result)
					let item = this[`fileList${event.name}`][fileListLen]
					this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: result
					}))
					fileListLen++
				}
				const imagesString = this.imgs.join(',');

				if (this.activeIndex === 0) {
					this.images = imagesString
				} else if (this.activeIndex === 1) {
					this.video = imagesString
				} else {
					this.voice = imagesString
				}
				console.log("图片，", this.images, "视频，", this.video, "音频，", this.voice)
			},
			uploadFilePromise(url) {
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: 'https://huiyuanzhifu.12d3.cn/api/Upload/img', // 仅为示例，非真实的接口地址
						pic: url,
						name: 'file',
						success: (res) => {
							setTimeout(() => {
								console.log("res", res)
								resolve(res.data.data)
							}, 1000)
						}
					});
					console.log("a", a)
				})
			},
			deleteSound(str) {
				this.videoPath = ''
				this.type = ''
			},
			deleteImage(index) {
				this.imgArr.splice(index, 1)
				this.maxImage++
				if (this.imgArr.length == 0) {
					this.type = ''
				}
			},
			// 上传音频
			uploadSound(str) {
			},
			// 音频播放
			soundPlay(type) {
				if (type == 1) {
					this.soundType = false
					innerAudioContext.src = this.soundPath
					innerAudioContext.play();
				} else {
					this.soundType = true
					innerAudioContext.stop();
				}
			},
			// 上传文件
			upload(str) {
				console.log(str, '传参')
				uploadImgVideo(str, this.maxImage >= 9 ? 9 : this.maxImage).then(res => {
					this.maxImage -= res.length
					this.type = str
					if (str == 'image') {
						this.imgArr = this.imgArr.concat(res)
					} else if (str == 'video') {
						if (!this.videoPath) { // 只有当视频路径为空时才更新
							this.videoPath = res[0]
						}
					}
				})
			},
			onUnload() {
				uni.$off('successPath')
			},
		}
	}
</script>

<style scoped lang="scss">
	::v-deep .u-cell__body {
		padding: 20rpx 0 !important;
		/* 修正为 20rpx */
	}

	::v-deep .u-collapse-item__content__text {
		padding: 0 !important;
	}

	.selected {
		background-color: #f9f9f9;
		/* 选中时背景色 */
		color: #f37462;
		/* 选中时字体颜色 */
	}

	.opusList {
		width: 100%;

		view {
			line-height: 2;
			font-size: 30rpx;
			text-indent: 2.5em;
		}
	}

	.opusList.active {
		/* 新增：选中项的样式 */
		background-color: #f9f9f9;
		/* Active background color */
		color: #ff6600;
		/* Active text color */
	}

	#posts_choose {
		width: 100%;


	}

	.posts_title {
		display: flex;
		align-items: center;
	}

	.comm {
		margin-top: 40rpx;
	}

	.posts_choose {
		width: 90%;
		margin: auto;

		.posts_choose_name {
			line-height: 3;
		}

		.posts_choose_tag {
			display: flex;
			justify-content: space-around;

			view {
				width: 80%;

			}
		}
	}

	.posts_all {
		width: 90%;
		margin: auto;

		.top {
			height: 80rpx;
			display: flex;
		}
	}

	.textarea {
		width: 90%;
		margin: auto;
		font-size: 24rpx;
		padding: 20rpx 0;

		.title {
			font-size: 35rpx !important;

			margin: 10rpx 0;
		}

		.title1 {
			font-size: 35rpx !important;
			margin: 10rpx 0;
			border-bottom: 2rpx #f1f1f1 solid;
		}

		.textCount {
			display: flex;
			justify-content: flex-end;
			color: #b7b7b7;
		}
	}

	.ImageUpload {
		width: 90%;
		margin: auto;

		.title {
			font-size: 35rpx;
		}

		.upload {
			display: flex;
			flex-wrap: wrap;
			margin: 30rpx 0;
			color: #ff6700;

			image {
				width: 200rpx;
				height: 200rpx;
				display: flex;
				margin: 0 20rpx;
			}
		}
	}

	.vote {
		width: 90%;
		margin: auto;

		.a {
			line-height: 2;
			text-indent: 2em;
		}

		.vote_title {
			font-size: 35rpx;
			line-height: 2;
		}

		.vote_content {
			.Titletext {
				font-size: 24rpx;
				color: #8f8f8f;
			}

			.inputStyle {
				width: 80%;
				background: #f7f7f7;
				margin: 15rpx 0;
			}

			.example-body {
				background-color: #fff;
				padding: 20rpx;
			}

		}

		.delayType {
			display: flex;
			align-items: center;

			.delay {
				width: 100%;
				display: flex;
				justify-content: space-between;
				align-items: center;
			}
		}

		.Permissions_type {
			width: 90%;
			margin-left: auto;
			margin-top: 20rpx;

			.PermissionsInput {
				width: 45%;
				display: flex;
				align-items: center;

				.custom-placeholder::placeholder {
					font-size: 24rpx;
					/* 设置placeholder文字大小 */
				}
			}
		}
	}

	.posts-button {
		width: 80%;
		margin: auto;

		button {
			width: 50%;
			height: 80rpx;
			line-height: 80rpx;
			font-size: 32rpx;
			color: #fff;
		}

		.sunbmit {
			margin: 40rpx 0;

			.custom-icon-dingshifabu {
				position: relative;
				left: 13rem;
				bottom: 1rem;
				// #ifdef H5
				left: 17rem;
				// #endif
			}

			button {
				border-color: #ff6600;
				background-color: #ff6600;
			}
		}

		.Save {
			button {
				border-color: #c9c9c9;
				background-color: #c9c9c9;
			}
		}
	}

	.icon-box {
		margin: 30rpx 50rpx;

		image {
			width: 50rpx;
			margin-right: 24rpx;

			&:last-child {
				margin-right: 0;
			}
		}
	}

	.info-box {
		margin-bottom: 20rpx;
		margin: 0 30rpx;
		padding: 20rpx 0;

		.image-list {
			display: flex;
			flex-wrap: wrap;

			.item {
				position: relative;
				width: 23%;
				height: 150rpx;
				margin: 1%;

				.image {
					width: 100%;
					height: 100%;
					border-radius: 20rpx;
				}

				.icon {
					width: 40rpx;
					position: absolute;
					top: 10rpx;
					right: 10rpx;
				}
			}
		}

		.video {
			width: 200rpx;
			height: 200rpx;

			video {
				position: relative;
				z-index: 1 !important;
				width: 100%;
				height: 100%;
			}

			.icon {
				z-index: 999999;
				width: 40rpx;
				height: 40rpx;
				position: absolute;
				top: 10rpx;
				right: 10rpx;
			}
		}

		.sound {
			position: relative;
			width: 200rpx;
			height: 200rpx;

			.sound-bg {
				width: 100%;
				height: 100%;
				border-radius: 20rpx;
			}

			.sound-bg::before {
				content: "";
				position: absolute;
				top: 0;
				left: 0;
				width: 100%;
				height: 100%;
				background-color: rgba(0, 0, 0, 0.3);
			}

			.icon {
				position: absolute;
				z-index: 99;
				width: 40rpx;
				top: 10rpx;
				right: 10rpx;
			}

			.play {
				position: absolute;
				top: 0;
				left: 0;
				width: 100rpx;
				height: 100rpx;
				margin-left: 50rpx;
				margin-top: 50rpx;
			}
		}
	}
</style>